﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Procure.Data.Context;

namespace Procure.Web.attribute
{
    public partial class EditAttribute : System.Web.UI.Page
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            ImageButton save = UmbracoPanel1.Menu.NewImageButton();
            save.ImageUrl = umbraco.GlobalSettings.Path + "/images/editor/save.gif";
            save.AlternateText = "Save";

            save.Click += new ImageClickEventHandler(save_Click);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ProcureDataContext context = DataFactory.GetDataContext();
                
                int id = int.Parse(Request["id"]);

                Procure.Data.Context.Attribute attr = context.Attributes.FirstOrDefault(a => a.Id == id);

                if (attr != null)
                {
                    AttributeName.Text = attr.Name;
                    var dataTypes = from dataType in context.DataTypes
                                    orderby dataType.Name
                                    select dataType;
                    DataTypeList.DataSource = dataTypes;
                    DataTypeList.DataBind();
                    DataTypeList.SelectedValue = attr.DataTypeId.ToString();
                }
            }
        }

        void save_Click(object sender, ImageClickEventArgs e)
        {
            int id = int.Parse(Request["id"]);
            ProcureDataContext context = DataFactory.GetDataContext();

            Procure.Data.Context.Attribute attr = context.Attributes.FirstOrDefault(a => a.Id == id);
            attr.Name = AttributeName.Text;
            attr.DataTypeId = Convert.ToInt32(DataTypeList.SelectedValue);

            context.SubmitChanges();
        }
    }
}